﻿using System.Windows;
using System.Windows.Input;

namespace T68Control.Procdure
{
    public static class LoadedBehavior
    {
        public static readonly DependencyProperty LoadedCommandProperty =
            DependencyProperty.RegisterAttached(
                "LoadedCommand",
                typeof(ICommand),
                typeof(LoadedBehavior),
                new PropertyMetadata(null, OnLoadedCommandChanged));

        public static void SetLoadedCommand(UIElement element, ICommand value)
        {
            element.SetValue(LoadedCommandProperty, value);
        }

        public static ICommand GetLoadedCommand(UIElement element)
        {
            return (ICommand)element.GetValue(LoadedCommandProperty);
        }

        private static void OnLoadedCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement frameworkElement)
            {
                frameworkElement.Loaded -= FrameworkElement_Loaded;
                if (e.NewValue is ICommand)
                {
                    frameworkElement.Loaded += FrameworkElement_Loaded;
                }
            }
        }

        private static void FrameworkElement_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement frameworkElement)
            {
                var command = GetLoadedCommand(frameworkElement);
                command?.Execute(null);
            }
        }
    }
}